#include <stdio.h>
#include <unistd.h>
#include "ohos_init.h"
#include "cmsis_os2.h"
#include <time.h>
#include <stdlib.h>

osThreadId_t task_1_id;
osThreadId_t task_2_id;
osSemaphoreId_t semaphore_id;

#define TOTAL_COUNT 10

// 随机时间释放信号量
void task_1(void)
{
    while(1){
        int random_time = rand() % 1000 + 100;
        osDelay(random_time);
        printf("[Task1]try to release semaphore.Waiting time from the last task is %dms.\n",random_time);
        if(osSemaphoreGetCount(semaphore_id)<TOTAL_COUNT){
            if(osSemaphoreRelease(semaphore_id)==osOK){
                printf("[Task1]semaphore is released. There are %d semaphore left.\n",osSemaphoreGetCount(semaphore_id));
            }
            else{
                printf("[Task1]semaphore release failed!\n");
            }
        }
    }
}

// 随机时间获取信号量
void task_2(void){
    while(1){
        int random_time = rand() % 1000 + 100;
        osDelay(random_time);
        printf("[Task2]try to get semaphore.Waiting time from the last task is %dms.\n",random_time);
        if(osSemaphoreGetCount(semaphore_id)>0){
            if(osSemaphoreAcquire(semaphore_id, osWaitForever)==osOK){
                printf("[Task2]get semaphore success. There are %d semaphore left.\n",osSemaphoreGetCount(semaphore_id));
            }
            else{
                printf("[Task2]get semaphore failed!\n");
            }
        }
    }

}

void count_semaphore_demo()
{
    time_t t;
    srand((unsigned) time(&t));
    semaphore_id = osSemaphoreNew(10, 5, NULL);
    if (semaphore_id == NULL) {
        printf("Semaphore create failed!\n");
    }
    else{
        printf("[Semaphore]semaphore_id:%d\n",semaphore_id);
    }
    
    osThreadAttr_t task_1_attr={
        .name="task_1",
        .stack_size=1024*8,
        .priority=osPriorityNormal,
    };
    task_1_id=osThreadNew((osThreadFunc_t)task_1,NULL,&task_1_attr);
    if(task_1_id==NULL){
        printf("[Task1]Thread create failed!\n");
    }
    else{
        printf("[Task1]task_1_id:%d\n",task_1_id);
    }
    osThreadAttr_t task_2_attr={
        .name="task_2",
        .stack_size=1024*8,
        .priority=osPriorityNormal1,
    };

    task_2_id=osThreadNew((osThreadFunc_t)task_2,NULL,&task_2_attr);
    if(task_2_id==NULL){
        printf("[Task2]Thread create failed!\n");
    }
    else{
        printf("[Task2]task_2_id:%d\n",task_2_id);
    }
}

SYS_RUN(count_semaphore_demo);